const dbConnect = require('../database/dbconfig');

// 1获取组织部门列表
let getCaseIssueList = async () => {
    let sql = 'SELECT * FROM issue';
    let sqlArr = [];
    let result = await dbConnect.SySqlConnect(sql, sqlArr);
    return result
}

// 2按部门索引获取子部门数据
let getCaseIssueFindId = async (id) => {
    let sql =
        `SELECT 
        	i.name AS 组织部门,
        	b.name AS 子部门
        FROM
        	branch AS b
        	INNER JOIN issue AS i ON b.c_id = i.id 
        WHERE
        	i.id = ? 
        ORDER BY
        	b.id `;
    let sqlArr = [id];
    let result = await dbConnect.SySqlConnect(sql, sqlArr);
    return result;

}

/**
 * 3新增部门
 * 1) 获取父部分索引
 * 2) 判断是否重名
 * 3) 创建部门 
 */

let createCaseIssue = async (name, parentId) => {
    let sql = `INSERT INTO branch (name,c_id) VALUES(?,?)`;
    let sqlArr = [name, parentId];
    let result = await dbConnect.SySqlConnect(sql, sqlArr);
    return result;

}

// 4删除部门
let deleteCaseIssue = async (parentId, id) => {
    let sql = `DELETE FROM branch WHERE (c_id=? and id=?) ORDER BY id`;
    let sqlArr = [parentId, id];
    let result = await dbConnect.SySqlConnect(sql, sqlArr);
    return result;
}

//5修改部门
let updateCaseIssue = (parentId, id, name) => {
    let sql = `UPDATE branch SET name=? WHERE (c_id=? and id=?) `;
    let sqlArr = [name, parentId, id];
    let result = dbConnect.SySqlConnect(sql, sqlArr);
    return result;
}

module.exports = {
    getCaseIssueList,
    getCaseIssueFindId,
    createCaseIssue,
    deleteCaseIssue,
    updateCaseIssue

}